package com.example.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.enums.ResultCode;
import com.example.common.redis.RedisService;
import com.example.friend.domain.question.Question;
import com.example.friend.mapper.question.QuestionMapper;
import com.example.security.exception.ServiceException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/3/27 19:51
 */
@Component
public class QuestionCacheManager {

    @Resource
    private RedisService redisService;

    @Resource
    private QuestionMapper questionMapper;

    //判断Redis中是否有数据
    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }


    //刷新缓存
    public void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId)
                .orderByDesc(Question::getCreateTime));

        if (CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        //尾插放到缓存里面
        redisService.rightPushAll(CacheConstants.QUESTION_LIST,questionIdList);
    }

    //从缓存中拿到当前questionId 的上一个id
    public String preQuestion(Long questionId) {
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        //当前题目是第一题
        if (index==0 || index == null){
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index-1,Long.class).toString();
    }

    //从缓存中拿到当前questionId的下一个id
    public String nextQuestion(Long questionId) {
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        //当前题目是最后一题
        Long lastIndex = getListSize()-1;
        if (index==lastIndex || index==null){
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index+1,Long.class).toString();
    }
}
